package com.hifar.test.api.example;

import com.hifar.test.api.constant.AuthConstants;
import com.hifar.test.api.util.AuthUtil;
import com.hifar.test.api.util.RSAUtil;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;

/**
 * 认证流程使用示例
 * 演示正确的RSA加密Basic认证流程
 */
public class AuthExample {
    
    private static final String BASE_URL = "http://localhost:8080/api/busi/test/api/data-receiver";
    
    /**
     * 示例1：生成正确的认证头
     */
    public static void exampleGenerateAuthHeader() {
        try {
            System.out.println("=== 生成认证头示例 ===");
            
            // 1. 使用工具类生成认证头
            String authHeader = AuthUtil.generateBasicAuth(
                AuthConstants.DEFAULT_USERNAME, 
                AuthConstants.DEFAULT_PASSWORD
            );
            
            System.out.println("生成的认证头: " + authHeader);
            
            // 2. 手动验证认证头生成过程
            System.out.println("\n--- 手动验证认证头生成过程 ---");
            
            // 步骤1：RSA加密密码
            String encryptedPassword = RSAUtil.encryptPassword(AuthConstants.DEFAULT_PASSWORD);
            System.out.println("1. RSA加密密码: " + encryptedPassword);
            
            // 步骤2：构造凭据（用户名:加密密码）
            String credentials = AuthConstants.DEFAULT_USERNAME + ":" + encryptedPassword;
            System.out.println("2. 构造凭据: " + credentials);
            
            // 步骤3：Base64编码
            String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());
            System.out.println("3. Base64编码: " + encodedCredentials);
            
            // 步骤4：添加Basic前缀
            String manualAuthHeader = "Basic " + encodedCredentials;
            System.out.println("4. 完整认证头: " + manualAuthHeader);
            
            // 验证两种方法结果一致
            System.out.println("5. 结果一致: " + authHeader.equals(manualAuthHeader));
            
        } catch (Exception e) {
            System.err.println("生成认证头失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 示例2：验证认证头
     */
    public static void exampleValidateAuthHeader() {
        try {
            System.out.println("\n=== 验证认证头示例 ===");
            
            // 1. 生成认证头
            String authHeader = AuthUtil.generateBasicAuth(
                AuthConstants.DEFAULT_USERNAME, 
                AuthConstants.DEFAULT_PASSWORD
            );
            
            System.out.println("认证头: " + authHeader);
            
            // 2. 验证认证头格式
            boolean isValidFormat = AuthUtil.isValidBasicAuth(authHeader);
            System.out.println("格式验证: " + isValidFormat);
            
            // 3. 提取凭据
            String credentials = AuthUtil.extractCredentials(authHeader);
            System.out.println("提取凭据: " + credentials);
            
            // 4. 解析用户名和加密密码
            String[] parts = credentials.split(":", 2);
            String username = parts[0];
            String encryptedPassword = parts[1];
            
            System.out.println("解析用户名: " + username);
            System.out.println("解析加密密码: " + encryptedPassword);
            
            // 5. 验证用户名
            boolean usernameValid = AuthConstants.DEFAULT_USERNAME.equals(username);
            System.out.println("用户名验证: " + usernameValid);
            
            // 6. 解密并验证密码
            String decryptedPassword = RSAUtil.decryptPassword(encryptedPassword);
            boolean passwordValid = AuthConstants.DEFAULT_PASSWORD.equals(decryptedPassword);
            System.out.println("解密后密码: " + decryptedPassword);
            System.out.println("密码验证: " + passwordValid);
            
            // 7. 最终验证结果
            boolean finalResult = usernameValid && passwordValid;
            System.out.println("最终验证结果: " + finalResult);
            
        } catch (Exception e) {
            System.err.println("验证认证头失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 示例3：使用认证头发送请求
     */
    public static void exampleSendAuthenticatedRequest() {
        try {
            System.out.println("\n=== 发送认证请求示例 ===");
            
            // 1. 生成认证头
            String authHeader = AuthUtil.generateBasicAuth(
                AuthConstants.DEFAULT_USERNAME, 
                AuthConstants.DEFAULT_PASSWORD
            );
            
            System.out.println("使用认证头: " + authHeader);
            
            // 2. 准备请求数据
            String requestBody = "{\n" +
                    "                    \"modelCode\": \"PROJECT_INFO\",\n" +
                    "                    \"dataStatus\": 1,\n" +
                    "                    \"data\": [\n" +
                    "                        {\n" +
                    "                            \"EMPLOYEE\": {\n" +
                    "                                \"user_id\": \"500847\",\n" +
                    "                                \"user_name\": \"张兴\",\n" +
                    "                                \"department_id\": \"6281\",\n" +
                    "                                \"secretLevel\": 5\n" +
                    "                            }\n" +
                    "                        }\n" +
                    "                    ]\n" +
                    "                }";
            
            // 3. 发送请求
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", authHeader);
            
            HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
            
            try {
                ResponseEntity<String> response = restTemplate.postForEntity(
                    BASE_URL + "/employee", 
                    requestEntity, 
                    String.class
                );
                
                System.out.println("请求成功:");
                System.out.println("状态码: " + response.getStatusCode());
                System.out.println("响应内容: " + response.getBody());
                
            } catch (Exception e) {
                System.out.println("请求失败（可能是服务未启动）: " + e.getMessage());
            }
            
        } catch (Exception e) {
            System.err.println("发送认证请求失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 示例4：测试错误的认证头
     */
    public static void exampleTestInvalidAuth() {
        try {
            System.out.println("\n=== 测试错误认证头示例 ===");
            
            // 1. 测试错误的用户名
            String wrongUsernameAuth = AuthUtil.generateBasicAuth("wronguser", AuthConstants.DEFAULT_PASSWORD);
            System.out.println("错误用户名认证头: " + wrongUsernameAuth);
            
            // 2. 测试错误的密码
            String wrongPasswordAuth = AuthUtil.generateBasicAuth(AuthConstants.DEFAULT_USERNAME, "wrongpass");
            System.out.println("错误密码认证头: " + wrongPasswordAuth);
            
            // 3. 测试格式错误的认证头
            String invalidAuth = "Bearer " + Base64.getEncoder().encodeToString("admin:admin".getBytes());
            System.out.println("格式错误认证头: " + invalidAuth);
            
            // 4. 验证这些认证头都会被拒绝
            System.out.println("错误用户名认证头格式: " + AuthUtil.isValidBasicAuth(wrongUsernameAuth));
            System.out.println("错误密码认证头格式: " + AuthUtil.isValidBasicAuth(wrongPasswordAuth));
            System.out.println("格式错误认证头格式: " + AuthUtil.isValidBasicAuth(invalidAuth));
            
        } catch (Exception e) {
            System.err.println("测试错误认证头失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 主方法，运行所有示例
     */
    public static void main(String[] args) {
        System.out.println("=== RSA加密Basic认证流程示例 ===\n");
        
        // 1. 生成认证头
        exampleGenerateAuthHeader();
        
        // 2. 验证认证头
        exampleValidateAuthHeader();
        
        // 3. 发送认证请求
        exampleSendAuthenticatedRequest();
        
        // 4. 测试错误认证
        exampleTestInvalidAuth();
        
        System.out.println("\n=== 所有示例执行完成 ===");
    }
}
